package com.thread.join;

import java.util.Date;
import java.util.concurrent.TimeUnit;

//t.join()方法阻塞调用此方法的线程(calling thread)，直到线程t完成，此线程再继续；通常用于在main()主线程内，等待其它线程完成再结束main()主线程。例如：
public class JoinTester01 implements Runnable {

	private String name;

	public JoinTester01(String name) {
		this.name = name;
	}

	public void run() {
		System.out.printf("%s begins: %s\n", name, new Date());
		try {
			TimeUnit.SECONDS.sleep(4);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.printf("%s has finished: %s\n", name, new Date());
	}

	public static void main(String[] args) {
		Thread thread1 = new Thread(new JoinTester01("One"));
		Thread thread2 = new Thread(new JoinTester01("Two"));
		thread1.start();
		thread2.start();

		//try {
			//thread1.join();
			//thread2.join();
		//} catch (InterruptedException e) {
			//e.printStackTrace();
		//}
		/**
		 * 上述代码如果没有join()方法，输出如下：

			Main thread is finished
			One begins: Wed Aug 28 10:21:36 CST 2013
			Two begins: Wed Aug 28 10:21:36 CST 2013
			Two has finished: Wed Aug 28 10:21:40 CST 2013
			One has finished: Wed Aug 28 10:21:40 CST 2013

			可以看出主线程main比其它两个线程先结束。
		 * */
		System.out.println("Main thread is finished");
	}

}